import {
	baseUrl,
	put
} from '@/common/utils/request';
import {
	post
} from '@/common/utils/request'
// WebSocket连接
let socketTask = null;
let isSocketOpen = false;
let messageCallback = null;
let userId = null;
let messageIdCounter = 0; // 用于生成唯一的消息ID
export const uploadFile = (tempFilePath) => {
	const token = uni.getStorageSync('token');
	const retoken = uni.getStorageSync('retoken');
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${baseUrl}/api/chat/upload`,
			filePath: tempFilePath,
			name: 'file',
			header: {
				authorization: 'Bearer ' + token,
				retoken: 'Bearer ' + retoken
			},
			success: (res) => {
				try {
					const result = JSON.parse(res.data)
					if (result.code === 200 && result.data) {
						resolve(result.data)
					} else {
						reject(new Error(result.message || '图片发送失败'))
					}
				} catch (e) {
					reject(new Error('上传响应解析失败'))
				}
			},
			fail: (err) => reject(err)
		})
	})
}

// 获取当前WebSocket连接实例
export const getSocketTask = () => {
	return socketTask;
};

// 检查WebSocket是否已连接
export const isWebSocketConnected = () => {
	return isSocketOpen;
};

// 设置当前用户ID
export const setUserId = (id) => {
	userId = id;
};

// 设置消息回调
export const setMessageCallback = (callback) => {
	messageCallback = callback;
};

// 创建WebSocket连接
export const connectWebSocket = (selfId) => {
	if (socketTask) {
		socketTask.close();
	}

	// 保存用户ID
	userId = selfId;

	// 构造WebSocket URL
	const wsUrl = `ws://localhost:8090/api/chat/${selfId}`;
	console.log('尝试连接WebSocket:', wsUrl);

	socketTask = uni.connectSocket({
		url: wsUrl,
		success: () => {
			console.log('WebSocket连接请求成功');
		},
		fail: (err) => {
			console.error('WebSocket连接请求失败:', err);
		}
	});

	socketTask.onOpen(() => {
		console.log('WebSocket连接已打开');
		isSocketOpen = true;

		// 通知连接成功
		if (messageCallback) {
			messageCallback({
				type: 'system',
				msg: '你已加入聊天室',
				time: new Date().toLocaleString()
			});
		}
	});

	socketTask.onError((err) => {
		console.error('WebSocket连接错误:', err);
		if (messageCallback) {
			messageCallback({
				type: 'error',
				msg: '连接聊天室失败，请检查网络！',
				time: new Date().toLocaleString()
			});
		}
	});

	socketTask.onClose(() => {
		console.log('WebSocket连接已关闭');
		isSocketOpen = false;

		// 通知连接关闭
		if (messageCallback) {
			messageCallback({
				type: 'system',
				msg: '你已离开聊天室',
				time: new Date().toLocaleString()
			});
		}
	});

	// 监听WebSocket消息
	socketTask.onMessage((res) => {
		try {
			const message = JSON.parse(res.data);
			console.log('收到WebSocket消息:', message);

			// 调用回调函数处理消息
			if (messageCallback) {
				messageCallback(message);
			}
		} catch (error) {
			console.error('解析WebSocket消息失败:', error);
		}
	});

	return socketTask;
};

// 发送消息
export const sendWebSocketMessage = (toId, message, userName, headImg) => {
	if (isSocketOpen && socketTask) {
		// 构造消息对象（符合规范格式）
		const msgData = {
			id: 'msg_' + Date.now() + '_' + (++messageIdCounter), // 生成唯一消息ID
			toId: toId || "all", // 空则群发
			fromId: userId,
			name: userName,
			headImg: headImg ||
				"https://esan688.oss-cn-beijing.aliyuncs.com/avatars/%E8%B6%85%E7%AE%A1/1754565535365_%E6%A2%A6%E8%88%9F.jpg", // 默认头像
			msg: message,
			time: new Date().toLocaleString(),
			type: "send"
		};

		socketTask.send({
			data: JSON.stringify(msgData),
			success: () => {
				console.log('消息发送成功');
			},
			fail: (err) => {
				console.error('消息发送失败:', err);
			}
		});

		return true;
	} else {
		console.error('WebSocket未连接');
		return false;
	}
};

// 关闭WebSocket连接
export const closeWebSocket = () => {
	if (socketTask) {
		socketTask.close();
		socketTask = null;
		isSocketOpen = false;
		messageIdCounter = 0; // 重置消息ID计数器
	}
};

// 获取聊天记录
export const getChatHistory = (chatId) => {
	return new Promise((resolve) => {
		try {
			// 从本地存储获取聊天记录
			const chatKey = `chat_${userId}_${chatId}`;
			const history = uni.getStorageSync(chatKey) || [];
			console.log(`从本地加载聊天记录: ${chatKey}`, history);
			resolve(history);
		} catch (error) {
			console.error('加载聊天记录失败:', error);
			resolve([]);
		}
	});
};

// 保存聊天记录
export const saveChatHistory = (chatId, messages) => {
	try {
		// 保存聊天记录到本地存储
		const chatKey = `chat_${userId}_${chatId}`;
		uni.setStorageSync(chatKey, messages);
		console.log(`聊天记录已保存到本地: ${chatKey}`, messages);
	} catch (error) {
		console.error('保存聊天记录失败:', error);
	}
};